import { JSBridge } from "./JSBridge";
import LoginBase from "./LoginBase";
import ADBase, { BannerPos } from "./ADBase";
import ShareBase from "./ShareBase";
import StorageUtils from "../StorageUtils";
import WeiXinShare from "./weixin/WeiXinShare";
import OppoLogin from "./oppo/OppoLogin";
import OppoAD from "./oppo/OppoAD";
import OppoShare from "./oppo/OppoShare";
import TouTiaoLogin from "./toutiao/TouTiaoLogin";
import TouTiaoAD from "./toutiao/TouTiaoAD";
import TouTiaoShare from "./toutiao/TouTiaoShare";
import OppoStatistic from "./oppo/OppoStatistic";
import { WeiXinConfig } from "./weixin/WeiXinConfig";
import { OppoConfig } from "./oppo/OppoConfig";
import { TouTiaoConfig } from "./toutiao/TouTiaoConfig";
import WeiXinUtils from "./weixin/WeiXinUtils";
import OppoUtils from "./oppo/OppoUtils";
import TouTiaoUtils from "./toutiao/TouTiaoUtils";
import QuLe from "./QuLe";
import FriendlyLinkDialog from "../../common/FriendlyLinkDialog";
import WeiXinLogin from "./weixin/WeiXinLogin";
import WeiXinAD from "./weixin/WeiXinAD";
import PopupAlert from "../components/PopupAlert";

export enum Platform {
    WeiXin, Oppo, TouTiao, Other
}

export const MaxCloseBannerTimes = 3;

export default class SDKManager {

    private static _instance: SDKManager = null;
    private constructor() { }
    static get instance() {
        if (!SDKManager._instance) {
            SDKManager._instance = new SDKManager();
        }
        return SDKManager._instance;
    }

    static closeBannerTimes: number = 0;

    //玩家分享5次后取消所有广澳
    static readonly KeySharedTimes = 'SharedTimes0';
    static get sharedTimes() { return StorageUtils.readNumber(SDKManager.KeySharedTimes); }
    static set sharedTimes(v: number) { StorageUtils.saveNumber(SDKManager.KeySharedTimes, v); }
    static get disableAllADAfter5Shares() { return SDKManager.sharedTimes >= 5; }

    private isInited = false;
    private _login: LoginBase = null;
    private _ad: ADBase = null;
    private _share: ShareBase = null;

    /** 获取当前平台类别（枚举 Platform） */
    static get platform(): Platform {
        if (JSBridge.isTouTiaoPlatform()) {
            return Platform.TouTiao;
        } else if (JSBridge.isOppoPlatform()) {
            return Platform.Oppo;
        } else if (JSBridge.isWeiXinPlatform()) {
            return Platform.WeiXin;
        }
        return Platform.Other;
    }

    get openid() { return this._login ? this._login.openid : ''; }
    get session() { return this._login ? this._login.session : ''; }
    get session2() { return this._login ? this._login.session2 : ''; }
    get loginname() { return this._login ? this._login.loginname : ''; }

    /** 当前是否已登录平台 */
    get isLogined() { return this._login && this._login.isLogined; }

    /** 游戏启动后初始化 */
    init() {
        if (this.isInited) {
            return;
        }
        console.log('SDK初始化');
        this.isInited = true;
        switch (SDKManager.platform) {
            case Platform.WeiXin:
                this._login = new WeiXinLogin();
                this._ad = new WeiXinAD();
                this._share = new WeiXinShare();
                break;
            case Platform.Oppo:
                this._login = new OppoLogin();
                this._ad = new OppoAD();
                this._share = new OppoShare();
                OppoStatistic.reportMonitor();
                break;
            case Platform.TouTiao:
                this._login = new TouTiaoLogin();
                this._ad = new TouTiaoAD();
                this._share = new TouTiaoShare();
                break;
        }
        if (this._share) {
            this._share.init(QuLe.instance.randomShareTitle);
        }
    }

    /** 显示Banner广告,登录成功返回true,否则返回false */
    login(onFinish: Function) {
        if (!this._login) {
            this.failLoginTip();
            onFinish && onFinish(false);
            return;
        }
        if (this.isLogined) {
            onFinish && onFinish(true);
            return;
        }
        this._login.login(onFinish);
    }

    /** 配置表里已配有广告ID */
    get haveADConfig(): boolean {
        return QuLe.instance.remoteConfig && QuLe.instance.remoteConfig.bannerId;
    }

    /** 显示Banner广告 */
    showBanner(position: BannerPos) {
        if (QuLe.instance.remoteConfig && !QuLe.instance.remoteConfig.banner) {
            return;
        }
        if (!this._ad) {
            this.failADTip();
            return;
        }
        this._ad.showBanner(position);
    }

    /** 重置Banner广告位置 */
    setBannerPos(position: BannerPos) {
        if (QuLe.instance.remoteConfig && !QuLe.instance.remoteConfig.banner) {
            return;
        }
        if (!this._ad) {
            this.failADTip();
            return;
        }
        this._ad.setBannerPos(position);
    }

    /** 隐藏Banner广告 */
    hideBanner(byPlayerClick: boolean) {
        if (!this._ad) {
            this.failADTip();
            return;
        }
        this._ad.hideBanner(byPlayerClick);
    }

    /** 显示激励广告 onClose(isEnded: boolean) */
    showRewardVideo(onClose: Function) {
        if (QuLe.instance.remoteConfig && !QuLe.instance.remoteConfig.video) {
            return;
        }
        if (!this._ad) {
            this.failADTip();
            if (onClose) {
                onClose(false);
            }
            return;
        }
        this._ad.showRewardVideo(onClose);
    }

    /** 显示插屏广告
     * @param 头条暂时不支持onError回调，故干脆不做任何回调，考虑官方SDK有Bug，后续再添加
     */
    showInsertAD() {
        if (QuLe.instance.remoteConfig && !QuLe.instance.remoteConfig.insert) {
            return;
        }
        if (!this._ad) {
            this.failADTip();
            return;
        }
        this._ad.showInsertAD(null);
    }

    /** 弹出分享 onShareFinish(over3Seconds: boolean) */
    share(onShareFinish: Function) {
        if (QuLe.instance.remoteConfig && !QuLe.instance.remoteConfig.share) {
            onShareFinish && onShareFinish(false);
            return;
        }
        if (!this._share) {
            this.failShareTip();
            onShareFinish && onShareFinish(false);
            return;
        }
        this._share.share(QuLe.instance.randomShareTitle, '', (over3Seconds: boolean) => {
            onShareFinish && onShareFinish(over3Seconds);
            if (!over3Seconds) {
                PopupAlert.show('未完成分享');
            }
        });
    }

    private failLoginTip() {
        console.log('平台：' + SDKManager.platform + ' 登录未初始化');
    }

    private failADTip() {
        console.log('平台：' + SDKManager.platform + ' 广告未初始化');
    }

    private failShareTip() {
        console.log('平台：' + SDKManager.platform + ' 分享未初始化');
    }

    /** 获取个平台互跳配置 */
    getAllGamesConfig(): any[] {
        switch (SDKManager.platform) {
            case Platform.WeiXin: return WeiXinConfig.AllGames;
            case Platform.Oppo: return OppoConfig.AllGames;
            case Platform.TouTiao: return TouTiaoConfig.AllGames;
            case Platform.Other: return WeiXinConfig.AllGames; // test
        }
        return null;
    }

    /** 跳转到同平台其他游戏 */
    navigateToOtherGame(data: any) {
        QuLe.instance.jumpdata(data.appId, (success: boolean) => {
            if (success) {
                console.log("navigateToOtherGame", data.appId);
            }
        });
        switch (SDKManager.platform) {
            case Platform.WeiXin: WeiXinUtils.navigateToOtherGame(data.appId); break;
            case Platform.Oppo: OppoUtils.navigateToOtherGame(data.package); break;
            case Platform.TouTiao:
                console.log('只能使用SDKManager.instance.showOtherGamesList()')
                break;
            case Platform.Other: break;
        }
    }

    /** 显示其他游戏跳转列表 */
    showOtherGamesDialog() {
        if (!QuLe.instance.remoteConfig) {
            console.error('远程配置文件未准备好')
            return;
        }
        if (!QuLe.instance.remoteConfig.friendLinkDialog) {
            console.error('游戏互跳已禁用')
            return;
        }
        switch (SDKManager.platform) {
            case Platform.WeiXin:
            case Platform.Oppo:
                FriendlyLinkDialog.show();
                break;
            case Platform.TouTiao:
                if (TouTiaoUtils.isIOS) {
                    console.log('头条在iOS上不支持打开互跳窗口');
                    return;
                }
                TouTiaoUtils.showOtherGamesDialog(TouTiaoConfig.appId);
                break;
            case Platform.Other: break;
        }
    }

    /** 
     * 各平台监听网络状态白改变
     * @param callback ( isNetworkOK : boolean )
     */
    listenNetworkStatusChange(callback: Function) {
        switch (SDKManager.platform) {
            case Platform.WeiXin:
                WeiXinUtils.listenNetworkStatusChange(callback);
                break;
            case Platform.TouTiao:
                TouTiaoUtils.listenNetworkStatusChange(callback);
                break;
        }
    }

}
